import socketserver
import threading

my_port1 = 19228
my_port2 = 22220
conn_port1_poll = []    # 19228 所有客户端 存放数组
conn_port2_poll = []    # 22220 所有客户端 存放数组
conn_err_poll = []  # 错误 存放数组
conn_wpf6_poll = []  # 老程序触摸屏 存放数组


class MyServer(socketserver.BaseRequestHandler):
    def handle(self):
        this_port = int('{}'.format(self.server.socket).split('laddr=')[1].split('>')[0].split(', ')[1].split(')')[0])
        if this_port == my_port1:
            conn_port1_poll.append(self)
        elif this_port == my_port2:
            conn_port2_poll.append(self)
        else:
            conn_err_poll.append(self)
        print('{0},{1} ...connected'.format(this_port, self.client_address))
        while True:
            # request.recv 方法接收客户端发来的消息
            try:
                data = self.request.recv(1024 * 1024)
            except Exception as e:
                print('接收异常{}'.format(e))
                break
            else:
                # 收到数据直接打印
                # print('{} ...{}'.format(self.client_address, data))
                if data == b'':
                    print('{}的{} ...发来了空数据'.format(this_port, self.client_address))
                    if this_port == my_port1:
                        conn_port1_poll.remove(self)
                    elif this_port == my_port2:
                        conn_port2_poll.remove(self)
                    else:
                        conn_err_poll.remove(self)
                    break
                elif data == b'exit\r\n':
                    print('端口{}的{} ...发来了{}'.format(this_port, self.client_address, data))
                    if this_port == my_port1:
                        conn_port1_poll.remove(self)
                        # 发送exit给客户端断开连接
                        self.request.sendall(data.decode('utf-8').encode('utf-8'))
                    elif this_port == my_port2:
                        conn_port2_poll.remove(self)
                        # 发送exit给客户端断开连接
                        self.request.sendall(data.decode('utf-8').encode('utf-8'))
                    else:
                        conn_err_poll.remove(self)
                        # 发送exit给客户端断开连接
                        self.request.sendall(data.decode('utf-8').encode('utf-8'))
                    break
                # elif data == b'shows\r\n':
                #     print('端口{}的{} ...发来了{}，请求查看端口1的链接设备'.format(this_port, self.client_address, data))
                #     str = []
                #     for i in conn_port1_poll:
                #         str = i.client_address
                #     self.request.sendall('{}\n'.format(str).encode('gb2312'))
                # # request.sendall 方法发送消息给客户端
                # elif data == b'showc\r\n':
                #     print('端口{}的{} ...发来了{}，请求查看端口2的链接设备'.format(this_port, self.client_address, data))
                #     str = []
                #     for i in conn_port2_poll:
                #         str.append(i.client_address)
                #     self.request.sendall('{}\n'.format(str).encode('gb2312'))
                # # request.sendall 方法发送消息给客户端
                # elif data == b'showe\r\n':
                #     print('端口{}的{} ...发来了{}，请求查看错误的链接设备'.format(this_port, self.client_address, data))
                #     str = []
                #     for i in conn_err_poll:
                #         str.append(i.client_address)
                #     self.request.sendall('{}\n'.format(str).encode('gb2312'))
                # # request.sendall 方法发送消息给客户端
                elif data == b'showallyy':
                    print('端口{}的{} ...发来了{}，请求查看所有的链接设备'.format(this_port, self.client_address, data))
                    str = []
                    for i in conn_port1_poll:
                        str.append(i.client_address)
                    self.request.sendall('端口1\n{}\n'.format(str).encode('gb2312'))
                    str = []
                    for i in conn_port2_poll:
                        str.append(i.client_address)
                    self.request.sendall('端口2\n{}\n'.format(str).encode('gb2312'))
                    str = []
                    for i in conn_err_poll:
                        str.append(i.client_address)
                    self.request.sendall('未分配端口\n{}\n'.format(str).encode('gb2312'))
                # request.sendall 方法发送消息给客户端
                elif data[0:3] == b'im ':
                    print('{}的{} ...发来了{}，这是心跳包，不做处理'.format(this_port, self.client_address, data))
                elif data[0:2] == b'06':
                    if data[2:8] == b'CLOSED':
                        print('{}的{} ...发来了{}，这是wpf6断开连接设备指令，暂时无效。'.format(this_port, self.client_address, data))
                        continue
                    else:
                        epname = ""
                        try:
                            epname = data.decode("utf-8")[2:8] + "C"
                        except Exception as e:
                            print("设备转换失败{}".format(data))
                            continue
                        epname = bytes().fromhex('AACC') + epname.encode('utf-8') + bytes().fromhex('55')
                        print('{}的{} ...发来了{}，这是wpf6连接车辆指令，转发{}'.format(this_port, self.client_address, data, epname))
                        for i in conn_port1_poll:
                            try:
                                i.request.sendall(epname)
                            except:
                                conn_port1_poll.remove(i)
                # elif data == b'im 1...':
                #     print('端口{}的{} ...发来了{}，这是心跳包，不做处理'.format(this_port, self.client_address, data))
                # elif data == b'im 2...':
                #     print('端口{}的{} ...发来了{}，这是心跳包，不做处理'.format(this_port, self.client_address, data))
                # elif data == b'im 3...':
                #     print('端口{}的{} ...发来了{}，这是心跳包，不做处理'.format(this_port, self.client_address, data))
                # elif data == b'im 4...':
                #     print('端口{}的{} ...发来了{}，这是心跳包，不做处理'.format(this_port, self.client_address, data))
                # elif data == b'im 5...':
                #     print('端口{}的{} ...发来了{}，这是心跳包，不做处理'.format(this_port, self.client_address, data))
                # elif data == b'im 6...':
                #     print('端口{}的{} ...发来了{}，这是心跳包，不做处理'.format(this_port, self.client_address, data))
                # elif data == b'im 7...':
                #     print('端口{}的{} ...发来了{}，这是心跳包，不做处理'.format(this_port, self.client_address, data))
                # elif data == b'im 8...':
                #     print('端口{}的{} ...发来了{}，这是心跳包，不做处理'.format(this_port, self.client_address, data))
                # # request.sendall 方法发送消息给客户端
                else:
                    print('{}/{}:\n\t\t\t\t\t\t{}/转发'.format(this_port, self.client_address, data))
                    if this_port == my_port1:
                        for i in conn_port2_poll:
                            try:
                                i.request.sendall(data)
                            except:
                                conn_port2_poll.remove(i)
                    elif this_port == my_port2:
                        for i in conn_port1_poll:
                            try:
                                i.request.sendall(data)
                            except:
                                conn_port1_poll.remove(i)

    def finish(self):
        print('{} ...finish'.format(self.client_address))


class MyThread (threading.Thread):
    def __init__(self, threadID, name, counter, port):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
        self.port = port

    def run(self):
        print("启动端口{}...".format(self.port))
        s = socketserver.ThreadingTCPServer(('', self.port), MyServer)
        s.serve_forever()


if __name__ == '__main__':
    # 创建新线程
    thread1 = MyThread(1, "Thread-1", 1, my_port1)
    thread2 = MyThread(2, "Thread-2", 2, my_port2)
    thread1.start()
    thread2.start()
